import React, { FunctionComponent, useState, } from 'react';
import { message, Divider, Button, Radio } from 'antd';
import type { RadioChangeEvent } from 'antd';
import UploadComponent from '@/components/upload';
import styles from './index.less';
import { createPortraitStyleTask } from '@/services/api';


// 导入图片
const images = [
  { name: '二次元', index: 2, image: require('../../../assets/images/人像风格重绘-二次元.png') },
  { name: '复古漫画', index: 0, image: require('../../../assets/images/人像风格重绘-复古漫画.png') },
  { name: '3D童话', index: 1, image: require('../../../assets/images/人像风格重绘-3D童话.png') },
  { name: '小清新', index: 3, image: require('../../../assets/images/人像风格重绘-小清新.png') },
  { name: '未来科技', index: 4, image: require('../../../assets/images/人像风格重绘-未来科技.png') },
  { name: '国风古画', index: 5, image: require('../../../assets/images/人像风格重绘-国画古风.png') },
  { name: '喜迎新年', index: 9, image: require('../../../assets/images/人像风格重绘-喜迎新年.png') },
  { name: '清雅国风', index: 8, image: require('../../../assets/images/人像风格重绘-清雅国风.png') },
  { name: '炫彩卡通', index: 7, image: require('../../../assets/images/人像风格重绘-炫彩卡通.png') },
  { name: '将军百战', index: 6, image: require('../../../assets/images/人像风格重绘-将军百战.png') },
  
];

const model = 'wanx-style-repaint-v1';

//支持选中示例图片，覆盖上传组件的图片
interface PortraitStylePanelProps {
  setImageUrl: React.Dispatch<React.SetStateAction<string | undefined>>;
  imageUrl: string | undefined;
  onTaskGenerated: (taskId: string, model: string) => void;
}

// 示例人像图片
const exampleImages = [
  'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250306/adcapp/20250305193106.jpg',
  'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250214/sjnwyi/1ae3f860-e390-468c-9f3b-b168bcc372e4-1.png',
];

// 风格参考图示例
const referenceExampleImages = [
  'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250306/zrxxki/20250305205359.jpg',
  'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241225/qufljx/%E4%BA%BA%E5%83%8F%E9%A3%8E%E6%A0%BC%E9%87%8D%E7%BB%98-%E9%A3%8E%E6%A0%BC%E9%80%89%E6%8B%A9%E7%A4%BA%E4%BE%8B2.jpg',
];

const PortraitStylePanel: FunctionComponent<PortraitStylePanelProps> = ({ setImageUrl, imageUrl, onTaskGenerated }) => {
  const [selectedTab, setSelectedTab] = useState('style');
  const [selectedStyleIndex, setSelectedStyleIndex] = useState<number | null>(null);
  const [referenceImageUrl, setReferenceImageUrl] = useState<string>();

  const onChange = ({ target: { value } }: RadioChangeEvent) => {
    if (value === selectedTab) {
      return; // 如果tab没有变化，直接返回
    }

    if (value === 'reference') {
      setSelectedStyleIndex(-1); // 切换到参考图tab时
    } else if (value === 'style') {
      setSelectedStyleIndex(null); // 从参考图tab切回时
      setReferenceImageUrl(''); // 清除参考图
    }

    setSelectedTab(value);
  };

  //全局信提示
  const [messageApi, contextHolder] = message.useMessage();


  const showError = (errorMessage: string) => {
    messageApi.open({
      type: 'error',
      content: errorMessage,
    });
  };


  //点击一次选中风格，再次点击取消选中
  const handleStyleSelect = (styleIndex: number) => {
    // 如果点击的是当前选中的风格，则取消选中
    if (selectedStyleIndex === styleIndex) {
      setSelectedStyleIndex(null);
    } else {
      // 否则选中新的风格
      setSelectedStyleIndex(styleIndex);
    }
    console.log(`Selected style index: ${styleIndex}`);
  };

  // 点击示例图片
  const handleExampleClick = (url: string) => {
    console.log('选中示例人像图片 URL:', url);
    setImageUrl(url);
  };

  //点击风格参考图示例
  const handleReferenceExampleClick = (url: string) => {
    console.log('设置风格参考图 URL:', url);
    setReferenceImageUrl(url);
  };

  const handleGenerate = async () => {
    if (!imageUrl) {
      showError('请上传人像图片');
      return;
    }

    if (selectedTab === 'style' && selectedStyleIndex === null) {
      showError('请选择人像风格');
      return;
    }

    if (selectedTab === 'reference' && !referenceImageUrl) {
      showError('请上传风格参考图');
      return;
    }

    try {
      const response = await createPortraitStyleTask(
        imageUrl,
        selectedStyleIndex === null ? -1 : selectedStyleIndex,
        selectedTab === 'reference' ? referenceImageUrl : ''
      );
      const task_id = response;
      onTaskGenerated(task_id, model);
    } catch (error) {
      console.error('请求错误:', error);
      showError('请求错误，请稍后重试');
    }
  };

  return (
    <>
      {contextHolder}
      <div className={styles.portraitStylePanel}>
        <div className={styles.portraitStyleUpload}>
          <span className={styles.uploadTitle}>上传人像图片</span>
          <UploadComponent imageUrl={imageUrl} setImageUrl={setImageUrl} />
          <div className={styles.uploadExample}>
            <Divider
              orientation="left"
              style={{
                fontSize: '12px',
                fontWeight: 'normal'
              }}
            >
              示例人像图片
            </Divider>
            <div className={styles.exampleImages}>
              {exampleImages.map((url, index) => (
                <img
                  key={index}
                  className={styles.exampleImage}
                  src={url}
                  onClick={() => handleExampleClick(url)}
                />
              ))}
            </div>
          </div>
        </div>

        <div className={styles.portraitStyleOptions}>
          <Radio.Group
            options={[
              { label: '选择人像风格', value: 'style' },
              { label: '上传风格参考图', value: 'reference' }
            ]}
            onChange={onChange}
            value={selectedTab}
            optionType="button"
            buttonStyle="solid"
            className={styles.radioGroup}
          />

          <div className={styles.optionsContainer}>
            {selectedTab === 'style' ? (
              <div className={styles.styleOptions}>
                {images.map((style) => (
                  <div
                    key={style.index}
                    className={`${styles.styleItem} ${selectedStyleIndex === style.index ? styles.selected : ''}`}
                    onClick={() => handleStyleSelect(style.index)}
                  >
                    <img src={style.image} alt={style.name} />
                    <p>{style.name}</p>
                  </div>
                ))}
              </div>
            ) : (
              <div className={styles.referenceContainer}>
                <div className={styles.referenceUpload}>
                  <UploadComponent
                    imageUrl={referenceImageUrl}
                    setImageUrl={setReferenceImageUrl}
                  />
                  <div className={styles.uploadExample}>
                    <Divider orientation="left" style={{ fontSize: '12px', fontWeight: 'normal' }}>可以试试这些风格哦～</Divider>
                    <div className={styles.exampleImages}>
                      {referenceExampleImages.map((url, index) => (
                        <img
                          key={index}
                          className={styles.exampleImage}
                          src={url}
                          onClick={() => handleReferenceExampleClick(url)}
                        />
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className={styles.portraitStyleFooter}>
          <Button type="primary" block onClick={handleGenerate} className={styles.generateButton}>
            立即生成
          </Button>
        </div>
      </div>
    </>
  );
};

export default PortraitStylePanel;
